#!/usr/bin/envpython
#-*-coding:utf-8-*-
import redis
import json
from pexpect import pxssh
import pexpect
import re
from dingyue import RedisHelper,loginredis
import time
import threading
def Re(res,total,id = "1"):
    if id == "1":
        data = re.findall(str(res),total)
    if id == "2":
        data = re.findall(str(res),total,re.S)
    return data
#执行命令
class linuxforssh:
    def __init__(self,ip,user,password,port):
        self.user = user
        self.ip = ip
        self.password = password
        self.port = port
        self.s = pxssh.pxssh()
    def autolink(self):
        try:
            self.s.login(self.ip, self.user, self.password,port=self.port)
            return True
        except Exception as e:
            print("连接失败%s"%(e))
        return False
    def sendcommend(self,commend):
        self.s.sendline(commend)
        if self.s.prompt():
            return bytes.decode(self.s.before)
        else:
            return "命令失败"
    def logout(self):
        self.s.logout()
#主机信息收集
class Host:
    def __init__(self,ip,root,password,port,caijitime,name):
        self.ip = ip
        self.port = port
        self.root = root
        self.password = password
        self.name = name
        self.caijitime = int(caijitime)
        try:
            self.ssh = linuxforssh(self.ip,self.root,self.password,self.port)
            self.ssh.autolink()
        except Exception as e:
            print("ssh连接失败",e)
        try:
            self.r = loginredis()
        except Exception as e:
            print("登入redis失败",e)
        self.r.set(self.name, 1)
        self.cpuname = self.name + "_cpu"
        self.memname = self.name + "_memory"
        self.netname = self.name + "_net"
        self.diskname = self.name + "_disk"
        self.timename = self.name + "_time"
        self.r.delete(self.cpuname,self.memname,self.diskname,self.timename,self.netname)
    #获取百分比使用率情况
    def memory(self):
        name = self.name + "_memory"
        total = Re("}.\s+(\d+)",self.ssh.sendcommend("""free -m|awk  '$1=="Mem:"{printf("%s",$2)}'"""))
        usemem = Re("}.\s+(\d+)",self.ssh.sendcommend("""free -m|awk  '$1=="Mem:"{printf("%s",$3)}'"""))
        baifenbi = int(int(usemem[0]) / int(total[0]) * 100)
        self.r.lpush(self.memname,baifenbi)
        return True
    #获取网络流入流出情况
    def network(self):
        data = Re("(\S+):\s+(\d+)\s+\d+\s+\d+\s+\d+\s+\d+\s+\d+\s+\d+\s+\d+\s+(\d+)",self.ssh.sendcommend("cat /proc/net/dev"))
        eth = {}
        for i in data:
            if i[0] == "lo":
                pass
            else:
                eth[i[0]] = [int(int(i[1]) / 1024), int(int(i[2]) / 1024)]
        neteth = json.dumps(eth)
        self.r.lpush(self.netname, neteth)
        return True
    #获取cpu使用百分比
    def cpu(self):
        data = Re("}.\s+(\S+)",self.ssh.sendcommend("cat /proc/loadavg | awk '{print $1}'"))
        self.r.lpush(self.cpuname,data[0])
        return True
    def Time_time(self):
        self.r.lpush(self.timename,time.time())
    #获取硬盘IO信息总表
    def disk(self):
        diskio = {}
        data = Re("(\S+)\s+\d+.\d+\s+\d+.\d+\s+\d+.\d+\s+\d+.\d+\s+(\d+.\d+)\s+(\d+.\d+)\s+\d+.\d+\s+\d+.\d+\s+\d+.\d+\s+(\d+.\d+)\s+(\d+.\d+)\s+(\d+.\d+)\s+(\d+.\d+)",self.ssh.sendcommend("iostat -x -m -d"))
        for i in data:
            diskio[i[0]] = {}
            diskio[i[0]]["rx"] = i[1]
            diskio[i[0]]["tx"] = i[2]
            diskio[i[0]]["r_wait"] = i[3]
            diskio[i[0]]["w_wait"] = i[4]
            diskio[i[0]]["svctm"] = i[5]
            diskio[i[0]]["util"] = i[6]
        diskmessage = json.dumps(diskio)
        self.r.lpush(self.diskname,diskmessage)
        return True
    def Start(self):
        while True:
            if bytes.decode(self.r.get(self.name)) =="1":
                time.sleep(self.caijitime)
                self.Time_time()
                self.memory()
                self.cpu()
                self.network()
                self.disk()
            elif bytes.decode(self.r.get(self.name)) =="0":
                break
        return True
class Totalport:
    def __init__(self,ip,root,password):
        self.ip = ip
        self.root = root
        self.password = password
        try:
            self.ssh = linuxforssh(self.ip,self.root,self.password,22)
            self.ssh.autolink()
        except Exception as e:
            print("ssh连接失败",e)
        try:
            self.r = loginredis()
        except Exception as e:
            print("登入redis失败",e)
    def portdata(self):
        data = Re("(\d+):\s+(\S+)\s+(\S+)",self.ssh.sendcommend("porterrshow"))
        while True:
            for i in data:
                name = str(self.ip + " "+i[0])
                self.r.lpush(name, i[1] + " "+i[2])
            time.sleep(30)

def Hostxinxi(ip,root,password,port,caijitime,name):
    obj = Host(ip,root,password,port,caijitime,name)
    obj.Start()
def pool_jieshou():
    obj = RedisHelper()
    redis_sub = obj.subscribe()
    while True:
        msg= redis_sub.parse_response()
        data =bytes.decode( msg[2])
        print(data)
        datajiexi = data.split(",")
        print(datajiexi)
        #服务器信息采集
        if  int(datajiexi[7]) == 1:
            ip = datajiexi[0]
            user = datajiexi[2]
            password = datajiexi[3]
            port = int(datajiexi[4])
            caijitime = datajiexi[5]
            print("ip地址:%s 用户名:%s 密码：%s 端口：%s  采集频率:%s "%(ip,user,password,port,caijitime))
            t1 = threading.Thread(target=Hostxinxi,args=(ip,user,password,port,caijitime,data))
            t1.start()
        elif int(datajiexi[7]) == 3:
            ip = datajiexi[0]
            user = datajiexi[2]
            password = datajiexi[3]
            slot = int(datajiexi[4])
            port = datajiexi[5]
            caijitime = datajiexi[6]
            print("ip地址:%s 用户名:%s 密码：%s 槽位：%s 端口：%s  采集频率:%s "%(ip,user,password,slot,port,caijitime))

# Hostxinxi("192.168.20.210","root","root",22,5,"sf")
if __name__ == "__main__":
    # pool_jieshou()
    a = Totalport("192.168.20.210","root","root")
    a.portdata()